﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TireBias.Models;
using System.Net;
using WinNemoLib;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data;

namespace TireBias.Controllers
{
    public class BiasTailController : Controller
    {
        //
        // GET: /BiasTail/

        public ActionResult Index()
        {
            ViewBag.Full = "F";
            TailModel md = new TailModel();
            List< TailModel.TailBias_DS> list =  md.SEL_KANBANPLAN(SessionBag.Current.biasno,"","","",false,true);
            if (list.Count <= 0)
            {
                list = new List<TailModel.TailBias_DS>();
            }
            return View(list);
        }

        public JsonResult Header_line(string biasno)
        {        
         
            List<BIASPLANModel.BIASPLAN_DS> list = new List<BIASPLANModel.BIASPLAN_DS>();
            BIASPLANModel mdSearch = new BIASPLANModel();
            list = mdSearch.GET_TOPCORDPLN_ACT("", "10", biasno, "L", "", true);
            return Json(list);   
        }

        public ActionResult CheckProcess(string biasno, string shift)
        {
                SessionBag.Current.biasno = biasno;
                SessionBag.Current.shift = shift;
                TailModel md = new TailModel();
                TailModel.TailBias_DS noFinish = md.GET_NO_FINISH(biasno);
                if (StrUtil.IsNotEmpty(noFinish._biasno))
                {
                    return RedirectToAction("INPUT_VALUE", new { dtplan=noFinish._plandt , itemno = noFinish._itemno , sitemno = noFinish._sitemno });
                }

                return RedirectToAction("INDEX");
        }

        public ActionResult GET_INF_STD()
        {
            ViewBag.Full = "F";
            TailModel md = new TailModel();
            List<TailModel.TailBias_DS> list = md.SEL_KANBANPLAN(SessionBag.Current.biasno,"","","",true,true);
            if (StrUtil.IsNotEmpty(list[0]._sampflag) || (StrUtil.IsEmpty(list[0]._infFile)))
            {
              return  RedirectToAction("GET_STD");
            }
            return View(list);
        }

        public ActionResult GET_STD()
        {
            ViewBag.Full = "F";
            TailModel md = new TailModel();
            List<TailModel.TailBias_DS> list = md.SEL_KANBANPLAN(SessionBag.Current.biasno, "", "", "", true,true);
            
            return View(list);
        }

        public ActionResult GetPDF_File(string nm, string sub,Boolean isSample=false)
        {

            if (isSample)
            {

                MemoryStream workStream = new MemoryStream();
                Document document = new Document();
                PdfWriter.GetInstance(document, workStream).CloseStream = false;

                document.Open();
                document.Add(new Paragraph("New Sample"));

                document.Close();

                byte[] byteInfo = workStream.ToArray();
                workStream.Write(byteInfo, 0, byteInfo.Length);
                workStream.Position = 0;

                return new FileStreamResult(workStream, "application/pdf");
            }
        try
            {

            var address = Dns.GetHostAddresses(Nemo.GetINI("File", "DNS"))[0];
            string path = @"\\" + address + @"\" + Nemo.GetINI("File", "FilePath");
        

      
            if (!WinNemoLib.DriveMapper.GetConnected(null, path))
            {
                DriveMapper.MapDrive(null, path, Nemo.GetINI("File", "USER"), Nemo.GetINI("File", "PWD"));
            }
                
                string file = path + @"\" + sub + @"\" + nm;
                FileInfo infile = new FileInfo(file);
                if (!infile.Exists)
                {

                    MemoryStream workStream = new MemoryStream();
                    Document document = new Document();
                    PdfWriter.GetInstance(document, workStream).CloseStream = false;

                    document.Open();
                    document.Add(new Paragraph("Cannot Open File !!!" + nm));

                    document.Close();

                    byte[] byteInfo = workStream.ToArray();
                    workStream.Write(byteInfo, 0, byteInfo.Length);
                    workStream.Position = 0;

                    return new FileStreamResult(workStream, "application/pdf");
                }
                return new FileContentResult(System.IO.File.ReadAllBytes(file), "application/pdf");
            }
            catch (Exception ex)
            {
                WinNemoLib.Nemo.Error(ex);
                throw;
            }
            
        }

        public JsonResult GET_ROLL(string dtPlan,string itemno, string sitemno,Boolean checknoValue=false){
            TailModel md = new TailModel();
            List<TailModel.PlyRoll_DS> list = md.SEL_PLYROLL(SessionBag.Current.biasno,dtPlan,itemno,sitemno,"",checknoValue);
            return Json(list);
           // return View(list);

        }

        public JsonResult GET_FORINPUT(string dtPlan,string itemno, string sitemno,string side)
        {            
            TailModel md = new TailModel();
            List<TailModel.PlyRoll_DS> list = md.SEL_PLYROLL(SessionBag.Current.biasno,dtPlan,itemno,sitemno,side); 
            return Json(list);     
        }
        
        [Authorize]
        public ActionResult INPUT_VALUE(string dtplan,string itemno,string sitemno)
        {
            ViewBag.Full = "F";
            TailModel md = new TailModel();
            List<TailModel.TailBias_DS> list = md.SEL_KANBANPLAN(SessionBag.Current.biasno,dtplan,itemno, sitemno, true);
            
            return View(list);
        }


        public JsonResult SAVE_PLYROLL(List<TailModel.PlyRoll_DS> theData)
        {
            if (theData == null)
            {
                return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
            }
            TailModel mdUpd = new TailModel();
            using (ConnectionWrapper cnn = Nemo.GetDefaultConfiguredDbConnectionWrapper())
            {
                cnn.Open();
                cnn.BeginTransaction();

                foreach (TailModel.PlyRoll_DS data in theData){
                    data._empname = User.Identity.Name.ToString();
                    if (!mdUpd.DEL_PLYROLL(cnn,data._biasno,data._plandt,data._itemno,data._sitemno,data._side,data._rollno))
                    {
                    cnn.RollbackTransaction();
                    return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
                    }

                    if (!mdUpd.Ins_Data(cnn, data))
                    {
                    cnn.RollbackTransaction();
                    return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
                    }
	            }
                  cnn.CommitTransaction();
                 return Json(new { success = 1, message = "บันทึกเรียบร้อย" });
            }
        }

        public JsonResult FINIS_SUB_STD(List<BIASSUBPlanModel.BIASSUBPlan_DS> thedata)
        {
            BIASSUBPlanModel mdSearch = new BIASSUBPlanModel();
            using (ConnectionWrapper cnn = Nemo.GetDefaultConfiguredDbConnectionWrapper())
            {
                cnn.Open();
                cnn.BeginTransaction();
                
                if (mdSearch.UPDATE_SUB_STATUS_BIAS(cnn, thedata[0],"F"))
                {
                    cnn.CommitTransaction();
                    return Json(new { success = 1, message = "" });

                }
                else
                {
                    cnn.RollbackTransaction();
                    return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
                }
            }

        }

        public JsonResult GET_EXP(string sizes,string topcode,string forming,string dtPlan)
        {
            TailModel md = new TailModel();
            DataTable dt = md.GET_EXP(sizes,topcode,forming,dtPlan);

            return Json(new { exp = DateUtil.ToDisplayDate(dt.Rows[0]["ExpDate"], DateUtil.eLanguage.EN)
                , cur = DateUtil.ToDisplayDate(dt.Rows[0]["CurDate"], DateUtil.eLanguage.EN)
                ,
                              dCur = dt.Rows[0]["dCur"],
                              mCur = dt.Rows[0]["mCur"],
                              shift=dt.Rows[0]["shift"]
            });
        }

    }
}
